<!DOCTYPE html>
<html lang="zh">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>imosVideoDemo</title>
    <link rel="shortcut icon" href="piv.ico" />
    <script type="text/javascript" src="../common/axios.min.js"></script>
    <script type="text/javascript" src="../common/forge.min.js"></script>
    <script type="text/javascript" src="../common/jquery-1.9.1.js"></script>
    <style>
      p,
      button {
        display: none;
      }
      body {
        padding: 0px !important;
        margin: 0px !important;
      }
      html,
      body,
      .forVideo,
      .full,
      iframe,
      .imosSdk-video {
        width: 100% !important;
        height: 100% !important;
        overflow: hidden;
      }
      iframe {
        border: none;
      }
      .imosSdk-video {
        border: none !important;
      }
      .imosVideo-localDownload-0 {
        position: relative !important;
        top: 50% !important;
        left: 50% !important;
        text-align: center !important;
        transform: translate(-50%, -50%) !important;
        margin: 0 !important;
      }
      .imosVideo-localDownload-1 {
        left: 50% !important;
        transform: translateX(-50%) !important;
        position: relative !important;
        margin: 0 !important;
      }
    </style>
  </head>
  <!-- 注意！！！！！！！！！ -->
  <!--
	以下imosSdk.html及imosSdk.min.js引用地址需更改
	imosSdk.min.js引用地址需与服务器版本一致
    流程 登录-》创建窗格
 -->

  <body onbeforeunload="onbeforeunload">
    <div
      id="videoBox"
      class="forVideo"
      style="
        display: flex;
        flex-flow: row wrap;
        justify-content: center;
        align-items: center;
      "
    ></div>
  </body>
  <script>
    // 监听页面错误
    window.onerror = function (msg, source, line, column, error) {
      console.info('yushi window.onerror ---', msg, source, line, column, error)
      // loadError()
    }
    // 监听父页面的消息
    window.addEventListener('message', listenerMessage)
    function menuMessage(e) {
      if (!faterNodeId) return
      e.preventDefault()
      window.parent.postMessage({
        message: {
          eventType: 'contextmenu',
          id: faterNodeId,
          name: faterNodeName,
          clientX: e.clientX,
          clientY: e.clientY,
          index: Number(areaId?.split('_')[1])
        }
      })
    }
    function debounce(func, wait, promptly = false) {
      let timeout = null
      return function () {
        let context = this
        let args = arguments
        function clear() {
          timeout = undefined
        }
        function exec() {
          func.apply(context, args)
        }
        if (promptly && !timeout) {
          exec()
        }
        if (timeout) clearTimeout(timeout)
        timeout = setTimeout(promptly ? clear : exec, wait)
      }
    }
    let isFull = false // 是否是全屏
    const setSize = debounce((e) => {
      if (!faterNodeId) return
      if (
        window.innerHeight === window.parent.innerHeight &&
        window.innerWidth === window.parent.innerWidth &&
        !isFull
      ) {
        // 全屏
        window.parent.postMessage({
          message: {
            eventType: 'selfFull',
            id: faterNodeId,
            index: Number(areaId?.split('_')[1])
          }
        })
        isFull = true
      } else if (
        (window.innerHeight !== window.parent.innerHeight ||
          window.innerWidth !== window.parent.innerWidth) &&
        isFull
      ) {
        // 退出全屏
        window.parent.postMessage({
          message: {
            eventType: 'selfNoFull',
            id: faterNodeId,
            index: Number(areaId?.split('_')[1])
          }
        })
        isFull = false
      }
    }, 100)
    function clickVideoBox(e) {
      if (!faterNodeId) return
      window.parent.postMessage({
        message: {
          eventType: 'click',
          id: faterNodeId,
          index: Number(areaId?.split('_')[1])
        }
      })
      // 点击宇视插件右上角关闭按钮 移除
      if (
        Array.from(e.target.classList).some(
          (item) => item === 'imosVideo-icon-close'
        )
      ) {
        window.parent.postMessage({
          message: {
            eventType: 'stopVideo',
            id: faterNodeId,
            index: Number(areaId?.split('_')[1])
          }
        })
      }
    }

    function loaded() {
      if (!faterNodeId) return
      window.parent.postMessage({
        message: {
          eventType: 'loaded',
          id: faterNodeId,
          index: Number(areaId?.split('_')[1])
        }
      })
    }
    function loadError(message) {
      if (!faterNodeId) return
      window.parent.postMessage({
        message: {
          eventType: 'error',
          message,
          id: faterNodeId,
          index: Number(areaId?.split('_')[1])
        }
      })
    }
    let isSpeed = false
    function handleKeyUp(e) {
      if (!faterNodeId) return
      if (e.key === 'Escape') {
        window.parent.postMessage({
          message: {
            eventType: 'Escape',
            id: faterNodeId,
            index: Number(areaId?.split('_')[1])
          }
        })
      } else if (e.keyCode === 32) {
        if (!isSpeed) {
          console.log('暂停')
          // 空格暂停
          pausePlay(iframeObj.id)
          isSpeed = true
        } else {
          console.log('播放')
          // 空格继续播放
          continuePlay(iframeObj.id)
          isSpeed = false
        }
      }
    }
    function fullScreen() {
      if (!faterNodeId) return
      window.parent.postMessage({
        message: {
          eventType: 'fullScreen',
          id: faterNodeId,
          index: Number(areaId?.split('_')[1])
        }
      })
    }
    function onbeforeunload() {
      console.log('销毁')
      document
        .getElementById('videoBox')
        .removeEventListener('contextmenu', menuMessage)
      document
        .getElementById('videoBox')
        .removeEventListener('click', clickVideoBox)
      document.removeEventListener('keyup', handleKeyUp)
      window.removeEventListener('message', listenerMessage)
      document
        .getElementById('videoBox')
        .removeEventListener('dblclick', fullScreen)
      window.removeEventListener('resize', setSize)
    }
    window.addEventListener('resize', setSize)
    // 触发右键事件 传回父网页 dashboard/VideoCustomMouseMenu 组件接收
    document
      .getElementById('videoBox')
      .addEventListener('contextmenu', menuMessage)
    document.getElementById('videoBox').addEventListener('click', clickVideoBox)
    document.addEventListener('keyup', handleKeyUp)
    document.getElementById('videoBox').addEventListener('dblclick', fullScreen)
    var iframeObj,
      dataList = {}
    var videoDom = document.getElementsByClassName('forVideo')[0]
    var videoNum = 0 //video的数量
    function getQueryString(key, url) {
      let winObj = arguments.length > 1 ? arguments[1] : window
      let reg = new RegExp('(^|\\?|&)' + key + '=([^&]*)(\\s|&|$)', 'i')
      if (arguments.length <= 1) {
        if (typeof winObj.location != 'object') {
          winObj = window
        }
        if (reg.test(winObj.location.href))
          return unescape(RegExp.$2.replace(/\+/g, ' '))
        return ''
      } else {
        if (reg.test(url)) return unescape(RegExp.$2.replace(/\+/g, ' '))
        return ''
      }
    }
    function formatTime(time, fmt = 'yyyy-MM-DD hh:mm:ss') {
      let ret
      let date = new Date(time)
      let opt = {
        'y+': date.getFullYear().toString(), // 年份
        'Y+': date.getFullYear().toString(), // 年份
        'M+': (date.getMonth() + 1).toString(), // 月份
        'D+': date.getDate().toString(), // 日
        'd+': date.getDate().toString(), // 日
        'h+': date.getHours().toString(), // 小时
        'm+': date.getMinutes().toString(), // 分
        's+': date.getSeconds().toString() // 秒
      }
      for (let k in opt) {
        ret = new RegExp('(' + k + ')').exec(fmt)
        if (ret) {
          fmt = fmt.replace(
            ret[1],
            ret[1].length === 1 ? opt[k] : opt[k].padStart(ret[1].length, '0')
          )
        }
      }
      return fmt
    }
    let isInit = true
    let faterNodeId = null
    let faterNodeName = null
    let areaId = null
    function listenerMessage(e) {
      console.log('宇视iframe', e.data)
      // if (!isInit) return
      if (e && e.data) {
        switch (e.data.action) {
          case 'init': //初始化
            //页面加载时创建播放实例初始化
            dataList = e.data.list
            const url = dataList.deviceUrl
            faterNodeId = dataList.id
            faterNodeName = dataList.name
            areaId = dataList.areaId
            if (!dataList.startTime || !dataList.endTime) {
              dataList.startTime = formatTime(
                new Date().getTime() - 1000 * 60 * 60 * 6
              )
              dataList.endTime = formatTime(new Date())
            }
            isInit = false
            console.log('dataList', dataList)
            if (iframeObj) {
              if (dataList.isplayback == 1) {
                //实时
                playLive(iframeObj.id)
              } else {
                replay(iframeObj.id)
              }
              loaded()
            } else {
              loadJS(
                'http://' + dataList.ip + ':7010/static/imosSdk.min.js',
                // "/yushi/app/imosSdk.min.js",
                function () {
                  init()
                }
              )
            }
            break
          case 'destroy':
            if (iframeObj?.id) {
              window.parent.postMessage({
                message: {
                  eventType: 'destroy',
                  id: faterNodeId,
                  index: Number(areaId?.split('_')[1])
                }
              })
              onbeforeunload()
              stopPlay(iframeObj.id)
            }
            break
          case 'real':
            if (iframeObj?.id) {
              playLive(iframeObj.id)
            }
            break
          case 'playback':
            dataList.startTime = e.data.startTime
            dataList.endTime = e.data.endTime
            if (iframeObj?.id) {
              replay(iframeObj.id)
            }
            break
          case 'download':
            startDownload()
            break
          case 'allResize': // 全部重新resize
            window.parent.postMessage({
              message: {
                eventType: 'allResize',
                id: faterNodeId,
                index: Number(areaId?.split('_')[1])
              }
            })
            break
        }
      }
    }
    //动态引入js http://10.10.10.2:7010/static/imosSdk.min.js
    function loadJS(url, callback) {
      var script = document.createElement('script'),
        fn = callback || function () {}
      script.type = 'text/javascript'
      script.src = url
      setTimeout(() => {
        //IE
        if (script.readyState) {
          script.onreadystatechange = function () {
            if (
              script.readyState == 'loaded' ||
              script.readyState == 'complete'
            ) {
              script.onreadystatechange = null
              fn()
            }
          }
        } else {
          //其他浏览器
          script.onload = function () {
            fn()
          }
          script.onerror = function () {
            loadError('宇视：imosSdk.min.js 加载失败，请检查网络环境')
          }
        }
        document.getElementsByTagName('head')[0].appendChild(script)
      }, 200)
    }
    //初始化
    function init() {
      try {
        var d = new Date(dataList.startTime)
        if (!dataList.endTime) {
          d.setTime(d.getTime() + 5 * 60 * 1000)
          dataList.endTime = d.Format('yyyy-MM-dd hh:mm:ss')
        }
      } catch (e) {
        loadError('宇视：插件初始化失败')
        //TODO handle the exception
      }
      login(dataList.ip, dataList.userName, dataList.userPass)
    }
    //#region 准备部分
    function login(ipaddr, username, password) {
      //服务器地址 用户名 密码
      axios({
        method: 'POST',
        url: 'http://' + ipaddr + ':7010/VIID/login/v2',
        headers: {
          'Content-Type': 'application/json; charset=utf8'
        },
        responseType: 'json'
      })
        .then(function (res) {
          var accessCode = res.data.AccessCode
          var md1 = forge.md.md5.create() //md5
          var md2 = forge.md.md5.create() //md5
          md1.update(password) //md5
          var passwordMd5 = md1.digest().toHex() //md5
          var base64Username = window.btoa(username)
          var loginSignatureTemp = base64Username + accessCode + passwordMd5
          md2.update(loginSignatureTemp) //md5
          var loginSignature = md2.digest().toHex() //md5
          var data = {
            UserName: username,
            AccessCode: accessCode,
            LoginSignature: loginSignature
          }
          axios({
            method: 'POST',
            url: 'http://' + ipaddr + ':7010/VIID/login/v2',
            headers: {
              'Content-Type': 'application/json; charset=utf8'
            },
            responseType: 'json',
            data: data
          })
            .then(function (r) {
              loginResult = r.data.ErrCode
              switch (
                loginResult //判断返回值：12351是‘用户不存在’；50004是‘密码错误，登录失败’
              ) {
                case 50004:
                  loadError('宇视：密码错误')
                  // alert('密码错误')
                  break
                case 12351:
                  loadError('宇视：用户不存在')
                  // alert('用户不存在')
                  break
                case undefined:
                  window.token = r.data.AccessToken
                  var vmip = ipaddr
                  imosSdk
                    .init(vmip, window.token, 9, '/yushi/app/imosSdk.html')
                    .then(function (res) {
                      creatWindow()
                      isInit = true
                    })
                    .catch(function (err) {
                      loadError('宇视：插件调用失败')
                      // alert('调用失败' + err)
                    })
                  break
              }
            })
            .catch(function (e) {
              loadError('宇视：服务器连接异常')
              // alert('服务器连接异常')
            })
        })
        .catch(function (error) {
          loadError('宇视：服务器连接异常')
          // alert('服务器连接异常')
        })
    }
    function creatWindow() {
      if (!window.token) {
        loadError('宇视：请先登录')
        // alert('请先登录')
        return
      }

      iframeObj = imosSdk.createPanelWindow()
      // 如果窗格创建已经到达上限
      if (iframeObj === null) {
        return
      }

      // createSpeDiv(iframeObj)
      // videoNum++
      videoDom.appendChild(iframeObj)
      if (dataList.isplayback == 1) {
        //实时
        playLive(iframeObj.id)
      } else {
        replay(iframeObj.id)
      }
      loaded()
    }

    /**
     * 创建包含了input和按钮的div
     * @param iframeObj iframe对象
     **/
    function createSpeDiv(iframeObj) {
      const beforeDom = document.getElementById('speDivId')
      if (beforeDom) beforeDom.remove()
      var divDom = document.createElement('div')
      divDom.id = 'speDivId'
      divDom.className = 'full'
      let date = new Date()
      divDom.innerHTML =
        '<p>摄像机编码:<input type="text" value="' +
        dataList.deviceCode +
        '" class="cameraCode' +
        videoNum +
        '" />' +
        '<button onclick="playLive(\'' +
        iframeObj.id +
        "'," +
        videoNum +
        ')">播放实况</button>' +
        '<button onclick="stopPlay(\'' +
        iframeObj.id +
        '\')">停止播放</button></p>' +
        '<p><input id="startd' +
        iframeObj.id +
        '" type="date" value="' +
        date.getFullYear() +
        '-' +
        ('0' + (date.getMonth() + 1)).substr(-2) +
        '-' +
        ('0' + date.getDate()).substr(-2) +
        '"/>' +
        '<input id="startt' +
        iframeObj.id +
        '" type="time" value="01:00:00" step="1"/>' +
        '<input id="endd' +
        iframeObj.id +
        '" type="date" value="' +
        date.getFullYear() +
        '-' +
        ('0' + (date.getMonth() + 1)).substr(-2) +
        '-' +
        ('0' + date.getDate()).substr(-2) +
        '" step="1"/>' +
        '<input id="endt' +
        iframeObj.id +
        '" type="time" value="23:59:59" step="1"/></p>' +
        '<p><button onclick="replay(\'' +
        iframeObj.id +
        "'," +
        videoNum +
        ')" >播放回放</button>' +
        '<button onclick="continuePlay(\'' +
        iframeObj.id +
        '\')">播放</button>' +
        '<button onclick="pausePlay(\'' +
        iframeObj.id +
        '\')">暂停</button>' +
        '<button onclick="playSpeed(\'' +
        iframeObj.id +
        '\')" id="' +
        iframeObj.id +
        '-speed">切换到2倍速</button>' +
        '<button onclick="singleFrame(\'' +
        iframeObj.id +
        '\')">单帧</button>' +
        '<button onclick="stepFrame(\'' +
        iframeObj.id +
        '\')">逐帧</button>' +
        '<button onclick="playcatch(\'' +
        iframeObj.id +
        '\')">抓拍</button></p>' +
        '<p><button onclick="addTitleBtn(\'' +
        iframeObj.id +
        '\')">增加自定义标题按钮</button>' +
        '<button onclick="delTitleBtn(\'' +
        iframeObj.id +
        '\')">删除标题按钮</button></p>' +
        '<p><button onclick="startPtzCtrl(\'' +
        videoNum +
        '\')">启动云台控制</button>' +
        '<button onclick="releasePtzCtrl(\'' +
        videoNum +
        '\')">释放云台控制</button>' +
        '<button onclick="sendPtzCtrl(\'' +
        videoNum +
        '\')">发送云台控制</button>' +
        '<button onclick="setPreset(\'' +
        videoNum +
        '\')">设置预置位</button>' +
        '</p>' +
        '<button onclick="usePreset(\'' +
        videoNum +
        '\')">使用预置位</button>' +
        '</p>' +
        '<p><button onclick="playStatus(\'' +
        iframeObj.id +
        '\')">状态输出到控制台</button>' +
        '<input type="text" value="' +
        (dataList.startTime || '') +
        '" id="recordJump"/>' +
        '<button onclick="recordJump(\'' +
        iframeObj.id +
        '\')">跳转播放</button></p>'
      divDom.appendChild(iframeObj)
      videoDom.appendChild(divDom)
      divDom = null

      if (dataList.isplayback == 1) {
        //实时
        playLive(iframeObj.id)
      } else {
        replay(iframeObj.id)
      }
      loaded()
    }

    //#endregion

    //#region 实况相关
    function playLive(iframeId) {
      if (!window.token) {
        loadError('宇视：请先登陆')
        // alert('请先登录')
        return
      }
      var cameraCode = dataList.deviceCode
      imosSdk.playLive(iframeId, cameraCode, faterNodeName, function (e) {}, 1)
      cameraCode = null
    }
    // 停止播放
    function stopPlay(iframeId) {
      if (!window.token) {
        loadError('宇视：请先登录')
        // alert('请先登录')
        return
      }
      imosSdk.playStop(iframeId, function (e) {})
    }
    // 跳转到指定时间点播放
    function recordJump(iframeId) {
      var jumoTime = document.getElementById('recordJump').value
      imosSdk.recordJump(iframeId, jumoTime, function (e) {
        if (e.ErrMsg) {
          loadError(`宇视：${e.ErrMsg}`)
          // alert(e.ErrMsg)
        }
      })
    }
    //回放
    function replay(iframeId, videoIndex) {
      if (!window.token) {
        loadError('宇视：请先登录')
        // alert('请先登录')
        return
      }
      var start = new Date(dataList.startTime)
      var end = new Date(dataList.endTime)
      var cameraCode = dataList.deviceCode
      var searchType = 2
      console.log('searchType', searchType)
      imosSdk.playRecord(
        iframeId,
        cameraCode,
        faterNodeName,
        start,
        end,
        function (e) {},
        searchType
      )
    }

    function queryCam() {
      var vmip = document.getElementById('ip').value
      var data = {
        org: 'iccsid',
        condition: {
          ItemNum: 3,
          Condition: [
            {
              QueryType: 256,
              LogicFlag: 0,
              QueryData: '1001'
            },
            {
              QueryType: 257,
              LogicFlag: 0,
              QueryData: '1'
            },
            {
              QueryType: 1,
              LogicFlag: 5,
              QueryData: ''
            }
          ],
          QueryCount: 1,
          PageFirstRowNumber: 0,
          PageRowNum: 20
        }
      }
      $.ajax({
        type: 'GET',
        url: 'http://' + vmip + ':7010/VIID/query',
        data: {
          org: data.org,
          condition: JSON.stringify(data.condition)
        },
        headers: {
          Authorization: window.token
        },
        contentType: 'application/json',
        success: function (res) {
          var arr = []
          if (res.ErrCode === 0) {
            var infoList = res.Result.InfoList
            var len = infoList.length
            for (var i = 0; i < len; i++) {
              if (infoList[i].ResItemV1.ResStatus === 1) {
                arr.push(infoList[i].ResItemV1.ResCode)
              }
            }
            camInput.value = arr.join(',')
          }
        }
      })
    }

    function startPtzCtrl() {
      var vmip = document.getElementById('ip').value
      var cameraCode = dataList.deviceCode
      $.ajax({
        type: 'POST',
        url: 'http://' + vmip + ':7010/VIID/ptz/start/' + cameraCode,
        headers: {
          Authorization: window.token
        },
        contentType: 'application/json',
        success: function (res) {
          if (res.ErrCode === 0) {
          }
        }
      })
    }

    function sendPtzCtrl() {
      var vmip = document.getElementById('ip').value
      var cameraCode = dataList.deviceCode
      axios({
        url: 'http://' + vmip + ':7010/VIID/ptz/ctrl/' + cameraCode,
        method: 'post',
        data: {
          PTZCmdID: 0x0502, //向右转动
          PTZCmdPara1: 6,
          PTZCmdPara2: 6,
          PTZCmdPara3: 2
        },
        headers: {
          Authorization: window.token,
          'Content-Type': 'application/json'
        }
      }).then(function (res) {
        if (res.data.ErrCode === 0) {
          //3秒后停止转动
          setTimeout(function () {
            axios({
              url: 'http://' + vmip + ':7010/VIID/ptz/ctrl/' + cameraCode,
              method: 'post',
              data: {
                PTZCmdID: 0x0901, //全部停止
                PTZCmdPara1: 6,
                PTZCmdPara2: 6,
                PTZCmdPara3: 2
              },
              headers: {
                Authorization: window.token,
                'Content-Type': 'application/json'
              }
            })
          }, 3000)
        }
      })
    }

    function releasePtzCtrl() {
      var vmip = document.getElementById('ip').value
      var cameraCode = dataList.deviceCode
      $.ajax({
        type: 'POST',
        url: 'http://' + vmip + ':7010/VIID/ptz/release/' + cameraCode,
        headers: {
          Authorization: window.token
        },
        contentType: 'application/json',
        success: function (res) {
          if (res.ErrCode === 0) {
          }
        }
      })
    }

    var presetCode = 1 //预置位编码
    function setPreset() {
      var vmip = document.getElementById('ip').value
      var cameraCode = dataList.deviceCode
      axios({
        url: 'http://' + vmip + ':7010/VIID/ptz/preset/set/' + cameraCode,
        method: 'post',
        data: {
          PresetValue: presetCode,
          PresetDesc: '预置位1'
        },
        headers: {
          Authorization: window.token,
          'Content-Type': 'application/json'
        }
      }).then(function (res) {
        if (res.data.ErrCode === 0) {
          presetCode = 1
        }
      })
    }

    function usePreset() {
      var vmip = document.getElementById('ip').value
      var cameraCode = dataList.deviceCode
      axios({
        url:
          'http://' +
          vmip +
          ':7010/VIID/ptz/preset/use/' +
          cameraCode +
          '/' +
          presetCode,
        method: 'GET',
        headers: {
          Authorization: window.token,
          'Content-Type': 'application/json'
        }
      })
    }

    //#region 本地播放器

    function openLocalPlayer() {
      var $iframe = document.createElement('iframe')
      $iframe.style.display = 'none'
      $iframe.src = 'imos://startXPWebPlayer'
      $iframe.onload = function () {
        var timer = setTimeout(function () {
          clearTimeout(timer)
          document.body.removeChild($iframe)
        }, 5000)
      }
      document.body.appendChild($iframe)
    }

    function downloadLocalPlayer() {
      // var vmip = document.getElementById('ip').value
      var host = location.host
      var aobj = document.createElement('a')
      aobj.download = '监控视频播放器.msi'
      aobj.href = `${host}/WEBPlayer.msi`
      document.body.appendChild(aobj)
      aobj.click()
      document.body.removeChild(aobj)
    }

    function checkLocalPlayer() {
      var btn = window.document.getElementById('imos_check_open_btn')
      imosSdk.checkOutWebPlayer().then(function () {
        if (res.ErrCode === 0) {
          btn.innerText = '打开播放器成功'
        } else {
          btn.innerText = res.ErrMsg
        }
      })
    }

    function playSpeed(iframeId) {
      var btn = document.getElementById(iframeId + '-speed')
      var speed = 2

      if (typeof btn.nextSpeed === 'number') {
        speed = btn.nextSpeed
      }
      imosSdk.recordSpeed(iframeId, speed, function (e) {})
      switch (speed) {
        case 1:
          btn.nextSpeed = 2
          btn.innerText = '切换到' + btn.nextSpeed + '倍速'
          break
        case 2:
          btn.nextSpeed = 4
          btn.innerText = '切换到' + btn.nextSpeed + '倍速'
          break
        case 4:
          btn.nextSpeed = 8
          btn.innerText = '切换到' + btn.nextSpeed + '倍速'
          break
        case 8:
          btn.nextSpeed = 1 / 8
          btn.innerText = '切换到' + btn.nextSpeed + '倍速'
          break
        case 1 / 8:
          btn.nextSpeed = 1
          btn.innerText = '切换到' + btn.nextSpeed + '倍速'
          break
        default:
          break
      }
    }

    function singleFrame(iframeId) {
      imosSdk.singleFrame(iframeId, function (e) {})
    }

    function stepFrame(iframeId) {
      imosSdk.stepFrame(iframeId, function (e) {})
    }

    function switchPlay(iframeId) {
      imosSdk.switchPlayStatus(iframeId, function (e) {})
    }

    function continuePlay(iframeId) {
      imosSdk.switchPlayStatus(iframeId, function (e) {}, true)
    }

    function pausePlay(iframeId) {
      imosSdk.switchPlayStatus(iframeId, function (e) {}, false)
    }

    function playStatus(iframeId) {
      imosSdk.playStatus(iframeId, function (e) {})
    }

    //#endregion

    function addTitleBtn(iframeId) {
      imosSdk.addTitleBtn(
        iframeId,
        {
          id: 'button1',
          className: '123123',
          iconUrl:
            '',
          tip: '自定义按钮'
        },
        function (el) {}
      )
    }

    function delTitleBtn(iframeId) {
      imosSdk.delTitleBtn(iframeId, 'button1', function (el) {})
    }

    function playcatch(iframeId) {
      imosSdk.playCatch(
        iframeId,
        function (e) {
          var arr = e.Img.split(','),
            mime = arr[0].match(/:(.*?);/)[1],
            bstr = atob(arr[1]),
            n = bstr.length,
            u8arr = new Uint8Array(n)
          while (n--) {
            u8arr[n] = bstr.charCodeAt(n)
          }
          var blob = new Blob([u8arr], {
            type: mime
          })
          var url = window.URL.createObjectURL(blob)
          var a = document.createElement('a')
          a.style.display = 'none'
          a.href = url
          a.download = '抓拍.jpg'
          document.body.appendChild(a)
          a.click()
          document.body.removeChild(a)
          window.URL.revokeObjectURL(url)
        },
        'image/jpeg'
      )
    }

    //#endregion

    //#region 下载
    function startDownload() {
      // var start = new Date(
      //   document.getElementById('downloadStartdate').value +
      //     ' ' +
      //     document.getElementById('downloadStarttime').value
      // )
      // var end = new Date(
      //   document.getElementById('downloadEnddate').value +
      //     ' ' +
      //     document.getElementById('downloadEndtime').value
      // )
      // var cameraCode = document.getElementById('downloadCode').value

      imosSdk.downloadRecord(
        dataList.deviceCode,
        dataList.startTime,
        dataList.endTime,
        function (e) {
          // document.getElementById('taskID').value = e.Taskid
        }
      )
    }
    function getDownloadStatus() {
      var taskId = document.getElementById('taskID').value
      imosSdk.getDownloadItemInfo(taskId, function (result) {
        if (result.ErrCode === 0) {
        } else {
        }
      })
    }
    function cancleDownload() {
      var taskId = document.getElementById('taskID').value
      imosSdk.cancelDownload(taskId, function (result) {
        if (result.ErrCode === 0) {
        } else {
        }
      })
    }
    /*
     * js由毫秒数得到年月日 使用： (new Date(arg)).Format("yyyy-MM-dd hh:mm:ss.S")
     */
    Date.prototype.Format = function (fmt) {
      var o = {
        'M+': this.getMonth() + 1, // 月份
        'd+': this.getDate(), // 日
        'h+': this.getHours(), // 小时
        'm+': this.getMinutes(), // 分
        's+': this.getSeconds(), // 秒
        'q+': Math.floor((this.getMonth() + 3) / 3), // 季度
        S: this.getMilliseconds() // 毫秒
      }
      if (/(y+)/.test(fmt))
        fmt = fmt.replace(
          RegExp.$1,
          (this.getFullYear() + '').substr(4 - RegExp.$1.length)
        )
      for (var k in o)
        if (new RegExp('(' + k + ')').test(fmt))
          fmt = fmt.replace(
            RegExp.$1,
            RegExp.$1.length == 1
              ? o[k]
              : ('00' + o[k]).substr(('' + o[k]).length)
          )
      return fmt
    }
    //#endregion
  </script>
  <!-- <script type="text/javascript" src="http://10.10.10.2:7010/static/imosSdk.min.js"></script> -->
</html>
